package com.xl6667.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
@Slf4j
public class controllerAdvice {
    @Pointcut(value = "execution(public * com.xl6667.controller.*.*(..))") //其中value可以写多种表达式定义切入点
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret;
        try {
            log.info("=======Start=======");
            handBefore(joinPoint);
            ret = joinPoint.proceed();
            handAfter(ret);
        } finally {

        }
        return ret;
    }
    private void handBefore(ProceedingJoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURI());
        // 打印 Http method
        log.info("HTTP Method    : {}",request.getMethod() );
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",joinPoint.getSignature().getDeclaringTypeName(), ((MethodSignature)joinPoint.getSignature()).getName() );
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());

    }

    private void handAfter(Object joinPoint) {
        // 打印出参
        log.info("Response       : {}",JSON.toJSONString(joinPoint) );
        // 结束后换行
        log.info("=======End=======" + System.lineSeparator());

    }


}
